package data

import (
	"061/Sgame/db"
	"061/Sgame/net"
	"061/Sgame/server/game/gameConfig"
	"061/Sgame/server/game/model"
	"log"
	"time"
)

// MapRoleCity 玩家城池
type MapRoleCity struct {
	//mutex		sync.Mutex	`gorm:"-"`
	CityId     int       `gorm:"column:cityId;primaryKey"`
	RId        int       `gorm:"column:rid"`
	Name       string    `gorm:"column:name;comment:城池名称;default:城池" validate:"min=4,max=20,regexp=^[a-zA-Z0-9_]*$"`
	X          int       `gorm:"type:int not null"`
	Y          int       `gorm:"type:int not null"`
	CurDurable int       `gorm:"column:cur_durable;comment:当前耐久"`
	CreatedAt  time.Time `gorm:"column:created_at"`
	OccupyTime time.Time `gorm:"column:occupy_time;comment:占领时间"`
	IsMain     int8      `gorm:"column:is_main;comment:是否是主城"`
}

func (m *MapRoleCity) TableName() string {
	return "map_role_city"
}

var RoleCityDao = &mapRoleCityDao{
	rcChan: make(chan *MapRoleCity, 100),
}

type mapRoleCityDao struct {
	rcChan chan *MapRoleCity
}

func (m *mapRoleCityDao) running() {
	for {
		select {
		case rc := <-m.rcChan:
			if rc.CityId > 0 {
				//where  city_id = ?
				err := db.GormDB.Model(rc).Where("id =?", rc.CityId).Updates(rc).Error
				if err != nil {
					log.Println("mapRoleCityDao running error", err)
				}
			}
		}
	}
}

func init() {
	go RoleCityDao.running()
}
func (m *MapRoleCity) ToModel() interface{} {
	p := model.MapRoleCity{}
	p.X = m.X
	p.Y = m.Y
	p.CityId = m.CityId
	p.UnionId = GetUnion(m.RId)
	p.UnionName = ""
	p.ParentId = 0
	p.MaxDurable = 1000
	p.CurDurable = m.CurDurable
	p.Level = 1
	p.RId = m.RId
	p.Name = m.Name
	p.IsMain = m.IsMain == 1
	p.OccupyTime = m.OccupyTime.UnixNano() / 1e6
	return p
}

func (m *MapRoleCity) IsWarFree() bool {
	//占领时间
	occupyTime := m.OccupyTime.Unix()
	cur := time.Now().Unix()
	if cur-occupyTime < gameConfig.Base.Build.WarFree {
		return true
	}
	return false
}

func (m *MapRoleCity) DurableChange(change int) {
	m.CurDurable += change
	if m.CurDurable < 0 {
		m.CurDurable = 0
	}
}

func (m *MapRoleCity) SyncExecute() {
	RoleCityDao.rcChan <- m
	m.Push()
}

/* 推送同步 begin */
func (m *MapRoleCity) IsCellView() bool {
	return true
}

func (m *MapRoleCity) IsCanView(rid, x, y int) bool {
	return true
}

func (m *MapRoleCity) BelongToRId() []int {
	return []int{m.RId}
}

func (m *MapRoleCity) PushMsgName() string {
	return "roleCity.push"
}

func (m *MapRoleCity) Position() (int, int) {
	return m.X, m.Y
}

func (m *MapRoleCity) TPosition() (int, int) {
	return -1, -1
}
func (m *MapRoleCity) Push() {
	net.Mgr.Push(m)
}
